package com.mmloo.common.service;

import com.alibaba.fastjson.JSON;
import com.mmloo.common.model.User;
import com.mmloo.common.repository.CURDRepository;
import com.mmloo.common.util.DataTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * Created by jessy on 2015/9/25.
 */
@Service
public class UserService {
    @Autowired
    CURDRepository curdRepository;

    /**
     * 生成用户id
     * @return
     * @throws Exception
     */
    public String  generateUserId() throws Exception {
        ArrayList arrayList = new ArrayList();
        arrayList.add(DataTable.USER_ID_SQUENCE.getBytes());
        curdRepository.incr(arrayList);
        return curdRepository.get(arrayList);
    }

    /**
     * 添加用户
     * @param user
     * @return
     * @throws Exception
     */
    public User save(User user) throws Exception {
        user.setId(generateUserId());
        String jsonString = JSON.toJSONString(user);
        ArrayList<byte[]> arrayList = new ArrayList<>();
        arrayList.add(DataTable.USER_DETAIL_DATA.getBytes());
        arrayList.add(user.getId().getBytes());
        arrayList.add(jsonString.getBytes());
        curdRepository.hset(arrayList);
        return user;
    }

    /**
     * 根据用户id获取用户
     * @param id
     * @return
     * @throws Exception
     */
    public User get(String id) throws Exception {
        ArrayList<byte[]> arrayList = new ArrayList<>();
        arrayList.add(DataTable.USER_DETAIL_DATA.getBytes());
        arrayList.add(id.getBytes());
        String value = curdRepository.hget(arrayList);
        User user = JSON.parseObject(value,User.class);
        if(user.getValid() == 0)
            return null;
        return user;
    }

    /**
     * 更新用户数据
     * @param user
     * @throws Exception
     */
    public void update(User user) throws Exception{
        ArrayList<byte[]> arrayList = new ArrayList<>();
        arrayList.add(DataTable.USER_DETAIL_DATA.getBytes());
        arrayList.add(user.getId().getBytes());
        arrayList.add(JSON.toJSONString(user).getBytes());
        curdRepository.hset(arrayList);
    }

    /**
     * 删除用户
     * @param user
     * @throws Exception
     */
    public void delete(User user) throws Exception{
        user.setValid(0);
        update(user);
    }
}
